﻿#include "clock.h"

namespace util {
// 返回当前时间
std::chrono::system_clock::time_point now() {
    return std::chrono::system_clock::now();
}

// 返回指定毫秒时长
std::chrono::milliseconds ms(int ms) {
    return std::chrono::milliseconds(ms);
}

bool is_today(long l_t) {
    time_t t = l_t;
    return is_today(t);
}

bool is_today(time_t t) {
    if ((long)t <= 0)
        return true;

    struct tm t_check_time;
    LOCALTIME(t, t_check_time);

    time_t    tt = time(NULL);
    struct tm t_current;
    LOCALTIME(tt, t_current);

    bool time_is_today = t_check_time.tm_year == t_current.tm_year &&
                         t_check_time.tm_mon == t_current.tm_mon &&
                         t_check_time.tm_mday == t_current.tm_mday;
    return time_is_today;
}

// 计算一个超时时长（单位：秒）
double timeout(double seconds) {
    return seconds * std::chrono::microseconds::period::den;
}

// 计算时间差值
intmax_t time_diff(std::chrono::system_clock::time_point start,
                   std::chrono::system_clock::time_point end) {
    return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
}

// 计算时间差值（单位：秒）
double time_diff_sec(std::chrono::system_clock::time_point start,
                     std::chrono::system_clock::time_point end) {
    auto c = time_diff(start, end);
    return (double)c * std::chrono::microseconds::period::num /
           std::chrono::microseconds::period::den;
}

// "%Y-%m-%d %H:%M:%S"
std::string time_to_str(const std_time_t& time) {
    char      _time[25] = {0};
    time_t    tt        = std::chrono::system_clock::to_time_t(time);
    struct tm local_time;
    LOCALTIME(tt, local_time);
    strftime(_time, 22, "%Y-%m-%d %H:%M:%S", &local_time);

    return std::string(_time);
}

// "%d-%02d-%02d %02d:%02d:%02d.%03d"
std::string time_to_str_ex(const std_time_t& time) {
    uint64_t mill =
        std::chrono::duration_cast<std::chrono::milliseconds>(time.time_since_epoch()).count() -
        std::chrono::duration_cast<std::chrono::seconds>(time.time_since_epoch()).count() * 1000;

    char      _time[25] = {0};
    time_t    tt        = std::chrono::system_clock::to_time_t(time);
    struct tm local_time;
    LOCALTIME(tt, local_time);
    // strftime(_time, 22, "%Y-%m-%d %H:%M:%S", local_time);
    sprintf_s(_time,
              "%d-%02d-%02d %02d:%02d:%02d.%03d",
              local_time.tm_year + 1900,
              local_time.tm_mon + 1,
              local_time.tm_mday,
              local_time.tm_hour,
              local_time.tm_min,
              local_time.tm_sec,
              mill);

    return std::string(_time);
}

std::string time_t_to_str(long time) {
    auto tp = std::chrono::system_clock::from_time_t(time);
    return time_to_str(tp);

    // return std::format("{:%Y-%m-%d} {:%T}", tp, tp);
}
}   // namespace util